package com.haixiaoke.saas.cleaner.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.haixiaoke.saas.cleaner.domain.Cleaner;
import com.haixiaoke.saas.cleaner.mapper.CleanerMapper;
import com.haixiaoke.saas.cleaner.service.ICleanerService;
import com.haixiaoke.saas.common.enums.CleanerEnum;
import com.haixiaoke.saas.common.exception.ServiceException;
import com.haixiaoke.saas.common.tenant.TenantContext;
import com.haixiaoke.saas.common.utils.DateUtils;
import com.haixiaoke.saas.house.domain.Estate;
import com.haixiaoke.saas.house.domain.House;
import com.haixiaoke.saas.house.domain.HouseInspection;
import com.haixiaoke.saas.house.domain.HouseSweep;
import com.haixiaoke.saas.house.service.IEstateService;
import com.haixiaoke.saas.house.service.IHouseInspectionService;
import com.haixiaoke.saas.house.service.IHouseService;
import com.haixiaoke.saas.house.service.IHouseSweepService;
import com.haixiaoke.saas.user.domain.BizUserBusiness;
import com.haixiaoke.saas.user.service.IBizUserBusinessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static org.apache.commons.collections.CollectionUtils.collect;

/**
 * 保洁人员信息Service业务层处理
 *
 * @author xiaolong
 * @date 2024-05-08
 */
@Service
public class CleanerServiceImpl implements ICleanerService {
    @Autowired
    private CleanerMapper cleanerMapper;
    @Autowired
    private IEstateService estateService;
    @Autowired
    private IBizUserBusinessService bizUserBusinessService;
    @Autowired
    private IHouseService houseService;
    @Autowired
    private IHouseInspectionService houseInspectionService;
    @Autowired
    private IHouseSweepService houseSweepService;

    /**
     * 查询保洁人员信息
     *
     * @param cleanerId 保洁人员信息主键
     * @return 保洁人员信息
     */
    @Override
    public Cleaner selectCleanerByCleanerId(Long cleanerId) {
        return cleanerMapper.selectCleanerByCleanerId(cleanerId);
    }

    /**
     * 查询保洁人员信息列表
     *
     * @param cleaner 保洁人员信息
     * @return 保洁人员信息
     */
    @Override
    public List<Cleaner> selectCleanerList(Cleaner cleaner) {
        return cleanerMapper.selectCleanerList(cleaner);
    }

    /**
     * 新增保洁人员信息
     *
     * @param cleaner 保洁人员信息
     * @return 结果
     */
    @Override
    public int insertCleaner(Cleaner cleaner) {
        checkout(cleaner);
        BizUserBusiness userBusiness = bizUserBusinessService.selectBizUserBusinessByUserId(cleaner.getCleanerUserId(), TenantContext.getTenantId());
        if (ObjectUtil.isEmpty(userBusiness)) {
            throw new ServiceException("企业用户不存在");
        }
        Cleaner byCleanerUserId = cleanerMapper.selectCleanerByCleanerUserId(cleaner.getCleanerUserId(), TenantContext.getTenantId());
        if (ObjectUtil.isNotEmpty(byCleanerUserId)) {
            throw new ServiceException("企业用户已存在");
        }
        if (cleaner.getCleanerScope().equals(CleanerEnum.CLEANER_SCOPE_ASSIGN.getValue())) {
            Estate estate = new Estate();
            estate.setEstateIds(cleaner.getEstateIds().split(","));
            List<Estate> estateList = estateService.selectEstateList(estate);
            if (CollectionUtil.isNotEmpty(estateList)) {
                cleaner.setEstateNames(estateList.stream().map(Estate::getEstateName).collect(Collectors.joining(",")));
            }
        }
        if (cleaner.getHouseInspectionState().equals(CleanerEnum.HOUSE_INSPECTION_STATE_OPEN.getValue()) && cleaner.getSweepState().equals(CleanerEnum.SWEEP_STATE_OPEN.getValue())) {
            cleaner.setCleanerType(CleanerEnum.CLEANER_TYPE_ALL.getValue());
            cleaner.setCleanerContent(CleanerEnum.CLEANER_TYPE_INSPECTION.getLabel() + "、" + CleanerEnum.CLEANER_TYPE_SWEEP.getLabel());
        } else {
            if (cleaner.getHouseInspectionState().equals(CleanerEnum.HOUSE_INSPECTION_STATE_OPEN.getValue())) {
                cleaner.setCleanerType(CleanerEnum.CLEANER_TYPE_INSPECTION.getValue());
                cleaner.setCleanerContent(CleanerEnum.CLEANER_TYPE_INSPECTION.getLabel());
            } else {
                cleaner.setCleanerType(CleanerEnum.CLEANER_TYPE_SWEEP.getValue());
                cleaner.setCleanerContent(CleanerEnum.CLEANER_TYPE_SWEEP.getLabel());
            }
        }

        cleaner.setCleanerName(userBusiness.getUserName());
        cleaner.setCreateTime(DateUtils.getNowDate());
        return cleanerMapper.insertCleaner(cleaner);
    }


    /**
     * 修改保洁人员信息
     *
     * @param cleaner 保洁人员信息
     * @return 结果
     */
    @Override
    public int updateCleaner(Cleaner cleaner) {
        Cleaner byCleanerId = cleanerMapper.selectCleanerByCleanerId(cleaner.getCleanerId());
        if (!TenantContext.getTenantId().equals(byCleanerId.getTenantId())) {
            return 0;
        }
        checkout(cleaner);
        if (cleaner.getCleanerScope().equals(CleanerEnum.CLEANER_SCOPE_ASSIGN.getValue())) {
            Estate estate = new Estate();
            estate.setEstateIds(cleaner.getEstateIds().split(","));
            List<Estate> estateList = estateService.selectEstateList(estate);
            if (CollectionUtil.isNotEmpty(estateList)) {
                cleaner.setEstateNames(estateList.stream().map(Estate::getEstateName).collect(Collectors.joining(",")));
            }
        } else {
            cleaner.setEstateNames(null);
            cleaner.setEstateIds(null);
        }
        if (cleaner.getHouseInspectionState().equals(CleanerEnum.HOUSE_INSPECTION_STATE_OPEN.getValue()) && cleaner.getSweepState().equals(CleanerEnum.SWEEP_STATE_OPEN.getValue())) {
            cleaner.setCleanerType(CleanerEnum.CLEANER_TYPE_ALL.getValue());
            cleaner.setCleanerContent(CleanerEnum.CLEANER_TYPE_INSPECTION.getLabel() + "、" + CleanerEnum.CLEANER_TYPE_SWEEP.getLabel());
        } else {
            if (cleaner.getHouseInspectionState().equals(CleanerEnum.HOUSE_INSPECTION_STATE_OPEN.getValue())) {
                cleaner.setCleanerType(CleanerEnum.CLEANER_TYPE_INSPECTION.getValue());
                cleaner.setCleanerContent(CleanerEnum.CLEANER_TYPE_INSPECTION.getLabel());
            } else {
                cleaner.setCleanerType(CleanerEnum.CLEANER_TYPE_SWEEP.getValue());
                cleaner.setCleanerContent(CleanerEnum.CLEANER_TYPE_SWEEP.getLabel());
            }
        }

        cleaner.setUpdateTime(DateUtils.getNowDate());
        return cleanerMapper.updateCleaner(cleaner);
    }

    /**
     * 批量删除保洁人员信息
     *
     * @param cleanerIds 需要删除的保洁人员信息主键
     * @return 结果
     */
    @Override
    public int deleteCleanerByCleanerIds(Long[] cleanerIds) {
        Cleaner cleaner = new Cleaner();
        cleaner.setTenantId(TenantContext.getTenantId());
        cleaner.setCleanerIds(cleanerIds);
        List<Cleaner> cleanerList = cleanerMapper.selectCleanerByCleanerIds(cleaner);
        if (cleanerList.size() < cleanerIds.length) {
            return 0;
        }
        List<HouseInspection> houseInspectionList = houseInspectionService.selectHouseInspectionByCleanerIds(cleanerIds);
        List<HouseSweep> houseSweepList = houseSweepService.selectHouseSweepByCleanerIds(cleanerIds);
        if (CollectionUtil.isNotEmpty(houseInspectionList) || CollectionUtil.isNotEmpty(houseSweepList)) {
            throw new ServiceException("用户还有未完成的打扫或验房单，请完成后再试");
        }
        return cleanerMapper.updateCleanerByCleanerIds(cleanerIds);
    }

    /**
     * 删除保洁人员信息信息
     *
     * @param cleanerId 保洁人员信息主键
     * @return 结果
     */
    @Override
    public int deleteCleanerByCleanerId(Long cleanerId) {
        return cleanerMapper.deleteCleanerByCleanerId(cleanerId);
    }

    /**
     * 获取企业用户信息
     */
    @Override
    public List<BizUserBusiness> getUserInfo() {
        return cleanerMapper.getUserInfo(TenantContext.getTenantId());
    }


    /**
     * 查询验房人员信息
     */
    @Override
    public List<Cleaner> cleanerUserInfo(Cleaner cleaner) {
        House house = houseService.selectHouseById(cleaner.getHouseId());
        if (ObjectUtil.isEmpty(house)) {
            throw new ServiceException("房源不存在");
        }
        ArrayList<Long> cleanerIds = new ArrayList<>();
        List<Cleaner> cleanerList = cleanerMapper.selectCleanerList(cleaner);
        if (CollectionUtil.isNotEmpty(cleanerList)) {
            for (Cleaner cleaner1 : cleanerList) {
                if (cleaner1.getCleanerScope().equals(CleanerEnum.CLEANER_SCOPE_ASSIGN.getValue())) {
                    if (cleaner1.getEstateIds().contains(house.getEstateId())) {
                        cleanerIds.add(cleaner1.getCleanerId());
                    }
                } else {
                    cleanerIds.add(cleaner1.getCleanerId());
                }
            }
        }
        cleanerList = cleanerList.stream().filter(c -> cleanerIds.contains(c.getCleanerId())).collect(Collectors.toList());
        return cleanerList;
    }

    @Override
    public Cleaner selectCleanerByCleanerUserId(Long cleanerUserId, String tenantId) {
        return cleanerMapper.selectCleanerByCleanerUserId(cleanerUserId, tenantId);
    }

    @Override
    public List<Cleaner> selectCleanerByCleanerList(Cleaner cleaner) {
        return cleanerMapper.selectCleanerByCleanerList(cleaner);
    }

    private void checkout(Cleaner cleaner) {
        if (cleaner.getCleanerUserId() == null) {
            throw new ServiceException("请选择用户");
        }
        if (StrUtil.isEmpty(cleaner.getHouseInspectionState()) && StrUtil.isEmpty(cleaner.getHouseInspectionState())) {
            throw new ServiceException("请设置人员职责");
        }
        if (cleaner.getHouseInspectionState().equals(CleanerEnum.HOUSE_INSPECTION_STATE_CLOSE.getValue()) && cleaner.getSweepState().equals(CleanerEnum.SWEEP_STATE_CLOSE.getValue())) {
            throw new ServiceException("请选择人员职责");
        }
        if (cleaner.getCleanerScope().equals(CleanerEnum.CLEANER_SCOPE_ASSIGN.getValue())) {
            if (StrUtil.isEmpty(cleaner.getEstateIds())) {
                throw new ServiceException("请选择指定楼盘");
            }
        }
    }
}
